import flwr as fl
from typing import Dict, List, Optional, Tuple
from config import MIN_CLIENTS, ROUNDS

def weighted_average(metrics: List[Tuple[int, Dict[str, float]]]) -> Dict[str, float]:
    """计算加权平均的评估指标"""
    total_samples = sum([num_samples for num_samples, _ in metrics])
    weighted_metrics = {}
    
    for metric_name in metrics[0][1].keys():
        weighted_sum = sum([m[metric_name] * num_samples for num_samples, m in metrics])
        weighted_metrics[metric_name] = weighted_sum / total_samples
    
    return weighted_metrics

def start_server(host: str, port: int):
    """启动联邦学习服务器"""
    strategy = fl.server.strategy.FedAvg(
        fraction_fit=1.0,  # 每轮参与训练的客户端比例
        fraction_evaluate=1.0,  # 每轮参与评估的客户端比例
        min_fit_clients=MIN_CLIENTS,  # 最小训练客户端数量
        min_evaluate_clients=MIN_CLIENTS,  # 最小评估客户端数量
        min_available_clients=MIN_CLIENTS,  # 最小可用客户端数量
        evaluate_metrics_aggregation_fn=weighted_average,  # 评估指标聚合函数
    )
    
    fl.server.start_server(
        server_address=f"{host}:{port}",
        config=fl.server.ServerConfig(num_rounds=ROUNDS),
        strategy=strategy
    ) 